package com.atgm.mall.gmmallperimall.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atgm.common.utils.GmMallUtils;
import com.atgm.common.utils.R;
import com.atgm.mall.gmmallperimall.dao.PeriGoodsDao;
import com.atgm.mall.gmmallperimall.dao.PeriGoodsImageDao;
import com.atgm.mall.gmmallperimall.dao.PeriGoodsThemeDao;
import com.atgm.mall.gmmallperimall.dao.PeriGoodsThemeRelaDao;
import com.atgm.mall.gmmallperimall.entity.PeriGoodsEntity;
import com.atgm.mall.gmmallperimall.entity.PeriGoodsImageEntity;
import com.atgm.mall.gmmallperimall.entity.PeriGoodsThemeEntity;
import com.atgm.mall.gmmallperimall.entity.PeriGoodsThemeRelaEntity;
import com.atgm.mall.gmmallperimall.feign.CouponFeignService;
import com.atgm.mall.gmmallperimall.feign.vo.FeignPeriGoodsSale;
import com.atgm.mall.gmmallperimall.service.PeriGoodsService;
import com.atgm.mall.gmmallperimall.vo.resp.PeriGoodsDetailVo;
import com.atgm.mall.gmmallperimall.vo.resp.PeriGoodsSaleVo;
import com.atgm.mall.gmmallperimall.vo.resp.PeriGoodsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PeriGoodsServiceImpl extends ServiceImpl<PeriGoodsDao, PeriGoodsEntity> implements PeriGoodsService {

    @Autowired
    private PeriGoodsThemeDao periGoodsThemeDao;

    @Autowired
    private PeriGoodsThemeRelaDao periGoodsThemeRelaDao;

    @Autowired
    @Qualifier("couponFeignService")
    private CouponFeignService couponFeignService;

    @Autowired
    private PeriGoodsImageDao periGoodsImageDao;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public List<PeriGoodsVo> queryGoodsListByTheme() {
        List<PeriGoodsVo> periGoodsVos = new LinkedList<>();
        //查询可以展示的商品主题信息
        QueryWrapper<PeriGoodsThemeEntity> periGoodsThemeEntityQueryWrapper = new QueryWrapper<>();
        periGoodsThemeEntityQueryWrapper.eq("is_show", 1);
        List<PeriGoodsThemeEntity> periGoodsThemeEntities = periGoodsThemeDao.selectList(periGoodsThemeEntityQueryWrapper);

        //获取关联的商品信息
        List<Long> themeIdList = new ArrayList<>();
        if (GmMallUtils.isNotEmpty(periGoodsThemeEntities)) {
            themeIdList = periGoodsThemeEntities.stream().map(PeriGoodsThemeEntity::getId).collect(Collectors.toList());
        }

        QueryWrapper<PeriGoodsThemeRelaEntity> periGoodsThemeRelaEntityQueryWrapper = new QueryWrapper<>();
        periGoodsThemeRelaEntityQueryWrapper.in("goods_theme_id", themeIdList);
        List<PeriGoodsThemeRelaEntity> relaEntityList = periGoodsThemeRelaDao.selectList(periGoodsThemeRelaEntityQueryWrapper);

        periGoodsThemeEntities.forEach(periGoodsThemeEntity -> {
            PeriGoodsVo periGoodsVo = new PeriGoodsVo();
            BeanUtils.copyProperties(periGoodsThemeEntity, periGoodsVo);
            //获取该主题下的商品信息
            List<Long> periGoodsIdList = new ArrayList<>();  //周边商品ids
            if (GmMallUtils.isNotEmpty(relaEntityList)) {
                periGoodsIdList = relaEntityList.stream().filter(item -> {
                    return item.getGoodsThemeId().equals(periGoodsThemeEntity.getId());
                }).map(PeriGoodsThemeRelaEntity::getPeriGoodsId).collect(Collectors.toList());
            }
            QueryWrapper<PeriGoodsEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", periGoodsIdList);
            IPage<PeriGoodsEntity> page = baseMapper.selectPage(new Page<PeriGoodsEntity>(0, 4), queryWrapper);
            List<PeriGoodsEntity> periGoodsEntities = page.getRecords();

            List<PeriGoodsSaleVo> periGoodsSaleVoList = new ArrayList<>();

            periGoodsEntities.forEach(periGoodsEntity -> {
                PeriGoodsSaleVo periGoodsSaleVo = new PeriGoodsSaleVo();
                BeanUtils.copyProperties(periGoodsEntity, periGoodsSaleVo);
                periGoodsSaleVoList.add(periGoodsSaleVo);
            });

            //获取周边商品优惠信息
            R r = couponFeignService.getPeriGoodsSaleByPeriGoodsIds(periGoodsIdList);
            if (0 == r.getCode()) {
                List<FeignPeriGoodsSale> feignPeriGoodsSaleList = r.getData(new TypeReference<List<FeignPeriGoodsSale>>() {});
                if (GmMallUtils.isNotEmpty(feignPeriGoodsSaleList)) {
                    //获取优惠的周边商品id
                    List<Long> periGoodsSaleIdList = feignPeriGoodsSaleList.stream().map(FeignPeriGoodsSale::getPeriGoodsId).collect(Collectors.toList());
                    periGoodsSaleVoList.forEach(periGoodsSaleVo -> {
                        if (periGoodsSaleIdList.contains(periGoodsSaleVo.getId())) {
                            //优惠价格
                            periGoodsSaleVo.setSeckillPrice(feignPeriGoodsSaleList.stream().filter(feignPeriGoodsSale -> {
                                return feignPeriGoodsSale.getPeriGoodsId().equals(periGoodsSaleVo.getId());
                            }).findAny().get().getSeckillPrice());
                            //活动数量
                            periGoodsSaleVo.setSeckillCount(feignPeriGoodsSaleList.stream().filter(feignPeriGoodsSale -> {
                                return feignPeriGoodsSale.getPeriGoodsId().equals(periGoodsSaleVo.getId());
                            }).findAny().get().getSeckillCount());
                            //每人限购数量
                            periGoodsSaleVo.setSeckillLimit(feignPeriGoodsSaleList.stream().filter(feignPeriGoodsSale -> {
                                return feignPeriGoodsSale.getPeriGoodsId().equals(periGoodsSaleVo.getId());
                            }).findAny().get().getSeckillLimit());
                            //优惠幅度
                            periGoodsSaleVo.setSeckillPercentage(feignPeriGoodsSaleList.stream().filter(feignPeriGoodsSale -> {
                                return feignPeriGoodsSale.getPeriGoodsId().equals(periGoodsSaleVo.getId());
                            }).findAny().get().getSeckillPercentage());
                        }
                    });
                }
            }

            periGoodsVo.setCount(page.getTotal());
            periGoodsVo.setGoodsList(periGoodsSaleVoList);
            periGoodsVos.add(periGoodsVo);
        });

        return periGoodsVos;
    }

    @Override
    public List<PeriGoodsEntity> queryGoodsInfoByIds(List<Long> ids) {
        QueryWrapper<PeriGoodsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        List<PeriGoodsEntity> list = baseMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public PeriGoodsDetailVo queryPeriGoodsDetailById(Long id) {
        PeriGoodsDetailVo periGoodsDetailVo = new PeriGoodsDetailVo();

        CompletableFuture<Void> periGoodsEntityFuture = CompletableFuture.runAsync( () -> {
            PeriGoodsEntity periGoodsEntity = baseMapper.selectById(id);
            BeanUtils.copyProperties(periGoodsEntity, periGoodsDetailVo);
        }, executor);

        //获取周边商品的图片
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            List<PeriGoodsImageEntity> imageEntityList = periGoodsImageDao.selectList(new QueryWrapper<PeriGoodsImageEntity>().eq("peri_goods_id", id));
            periGoodsDetailVo.setImages(imageEntityList);
        }, executor);

        //获取该周边商品的优惠价格
        CompletableFuture<Void> periGoodsSaleFuture = CompletableFuture.runAsync(() -> {
            R r = couponFeignService.getPeriGoodsSaleByPeriGoodsIds(Arrays.asList(id));
            if (0 == r.getCode()) {
                List<FeignPeriGoodsSale> periGoodsSaleList = r.getData(new TypeReference<List<FeignPeriGoodsSale>>() {
                });
                if (GmMallUtils.isNotEmpty(periGoodsSaleList)) {
                    FeignPeriGoodsSale feignPeriGoodsSale = periGoodsSaleList.get(0);
                    periGoodsDetailVo.setSeckillCount(feignPeriGoodsSale.getSeckillCount());
                    periGoodsDetailVo.setSeckillPrice(feignPeriGoodsSale.getSeckillPrice());
                    periGoodsDetailVo.setSeckillPercentage(feignPeriGoodsSale.getSeckillPercentage());
                    periGoodsDetailVo.setSeckillLimit(feignPeriGoodsSale.getSeckillLimit());
                }
            }
        }, executor);

        try {
            CompletableFuture.allOf(periGoodsEntityFuture, imagesFuture, periGoodsSaleFuture).get();
        } catch (InterruptedException e) {
            log.error("异步获取周边商品详情失败");
        } catch (ExecutionException e) {
            log.error("异步获取周边商品详情失败");
        }

        return periGoodsDetailVo;
    }
}
